package com.ruoyi.common.utils.excelPdfWord;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.ruoyi.common.utils.DateUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xumh
 * @title: PdfUtil
 * @projectName ruoyi
 * @description: TODO
 * @date 2024/12/2415:17
 */
public class PdfUtil {

    /**
     * 将数据导出为pdf文件
     * @param response
     * @param filePath 文件路径
     * @param fontPath 字体文件存放路径（一般固定放置服务器某个位置）
     * @param map 业务数据
     * @throws Exception
     */
    public static void dataToPdf(HttpServletResponse response,String filePath, String fontPath,Map<String,Object> map) throws Exception{
        // 加载字体
        PdfFont font = PdfFontFactory.createFont(fontPath);
        String fileName = URLEncoder.encode("test.pdf", "UTF-8");
        // 创建PDF文档
        PdfWriter writer = new PdfWriter(filePath);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);

        //创建一个简单的4列表格 标题加粗 居中
        Table table0= new Table(UnitValue.createPercentArray(4)).useAllAvailableWidth();
        table0.addCell("标题1");
        table0.addCell("标题2");
        table0.addCell("标题3");
        table0.addCell("标题4");
        table0.setFont(font);
        table0.setBold();
        table0.setTextAlignment(TextAlignment.CENTER);
        document.add(table0);

        //内容文字居中显示 不加粗
        Table table1= new Table(UnitValue.createPercentArray(4)).useAllAvailableWidth();
        //第一行
        table1.addCell(map.get("info1").toString());
        table1.addCell(map.get("info2").toString());
        table1.addCell(map.get("info3").toString());
        table1.addCell(map.get("info4").toString());
        //第二行
        table1.addCell(map.get("info5").toString());
        table1.addCell(map.get("info6").toString());
        table1.addCell(map.get("info7").toString());
        table1.addCell(map.get("info8").toString());
        table1.setFont(font);
        table1.setTextAlignment(TextAlignment.CENTER);
        document.add(table1);

        //中间文字分割一行 加粗 居中
        Table table2 = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        table2.addCell("设备清单");
        table2.setFont(font);
        table2.setBold();
        table2.setTextAlignment(TextAlignment.CENTER);
        document.add(table2);

        //设备清单：创建一个简单的4列表格
        Table table3 = new Table(UnitValue.createPercentArray(4)).useAllAvailableWidth();
        table3.addCell("设备参数");
        table3.addCell("设备参数");
        //.....
        table3.setTextAlignment(TextAlignment.CENTER);
        table3.setFont(font);
        document.add(table3);
        // 关闭文档
        document.close();
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        File file = new File(filePath);
        InputStream stream = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte buff[] = new byte[1024];
        int length = 0;
        while ((length = stream.read(buff)) > 0) {
            out.write(buff,0,length);
        }
        stream.close();
        out.close();
        out.flush();
    }

    /**
     * 将数据填充到PDF
     * @param response
     * @param fontPath 字体文件路径
     * @param filePath 文件路径
     * @param fenGeName 分割行名称
     * @param title_span 标题列数
     * @param content_span 内容列数
     * @param map      对象数据 title1 - 4 标题  content1 - 4 内容
     * @param list     字符串数组
     */
    public static void exportPdf(HttpServletResponse response, String fontPath, String filePath,
                                 String fenGeName,int title_span, int content_span,
                                 Map<String, Object> map,List<String> list) throws Exception{
        // 加载字体
        PdfFont font = PdfFontFactory.createFont(fontPath);
        String fileName = URLEncoder.encode("test.pdf", "UTF-8");
        // 创建PDF文档
        PdfWriter writer = new PdfWriter(filePath);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);

        //标题：创建一个4列表格  文字居中 加粗
        Table table0= new Table(UnitValue.createPercentArray(title_span)).useAllAvailableWidth();
        for (int i=1;i<=title_span;i++){
            table0.addCell(map.get("title"+i).toString());
        }
        table0.setFont(font); //字体
        table0.setBold(); //加粗
        table0.setTextAlignment(TextAlignment.CENTER); //居中
        document.add(table0);

        //内容：创建一个4列表格  文字居中
        Table table1= new Table(UnitValue.createPercentArray(title_span)).useAllAvailableWidth();
        for (int i=1;i<=title_span;i++){
            table1.addCell(map.get("content"+i).toString());
        }
        table1.setFont(font); //字体
        table1.setTextAlignment(TextAlignment.CENTER); //居中
        document.add(table1);


        //分割行：创建一个1列表格 文字居中 加粗
        Table table2 = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        table2.addCell(fenGeName);// 行内文字
        table2.setFont(font); //字体
        table2.setBold(); //加粗
        table2.setTextAlignment(TextAlignment.CENTER); //居中
        document.add(table2);

        //内容：创建一个n列表格  文字居中
        Table table3= new Table(UnitValue.createPercentArray(content_span)).useAllAvailableWidth();
        list.forEach(item -> {
            table3.addCell(item);
        });
        table3.setFont(font); //字体
        table3.setTextAlignment(TextAlignment.CENTER); //居中
        document.add(table3);

        // 关闭文档
        document.close();

        if (response!=null){
            response.setContentType("application/pdf");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="+fileName);
            File file = new File(filePath);
            InputStream stream = new FileInputStream(file);
            ServletOutputStream out = response.getOutputStream();
            byte buff[] = new byte[1024];
            int length = 0;
            while ((length = stream.read(buff)) > 0) {
                out.write(buff,0,length);
            }
            stream.close();
            out.close();
            out.flush();
        }
    }

    public static void main(String[] args) throws Exception{
        String file="D:\\360MoveData\\Users\\sxah-02\\Desktop\\export-001.pdf";
        String font="D:\\360MoveData\\Users\\sxah-02\\Desktop\\gkai00mp-2.ttf";
        Map<String, Object> map = new HashMap<>();
        for (int i=1;i<=4;i++){
            map.put("title"+i, "标题"+i);
            map.put("content"+i, "内容"+i);
        }
        List<String> list = new ArrayList<>();
        for (int i=1;i<=40;i++){
            list.add("xzd001001-"+i);
        }
        exportPdf(null, font, file, "分割行", 4, 4, map, list);
    }
}
